<template>
  <div class="main-cls">
    <!-- 标题 -->
    <div class="title-cls">聊一聊</div>

    <!-- 在线人数 -->
    <div style="height: 3%">
      <span style="float: left" class="onlineCount">
        在线小姐姐：
        <el-text class="mx-1" type="success">{{ count }}</el-text>
      </span>

      <span style="float: right" class="onlineCount">
        {{ date }}
      </span>

    </div>

    <!-- 消息 -->
    <div class="content-cls" ref="content">
      <el-scrollbar ref="myScrollbar" style="height: 100%">

        <div :class="item.sender === name ? 'content-right' : 'content-left' " v-for="(item, index) in msgRecord"
          :key="index">
          <span class="itime">
            {{ item.itime }} {{item.ip ? "（"+item.ip+"："+item.region+"）" : ''}}
          </span>
          <span>
            {{ item.sender }} : <el-tag size="small" round>{{ item.content }}</el-tag>
          </span>
        </div>

      </el-scrollbar>
    </div>


    <!-- 输入消息 -->
    <div class="mtop" style="height: 5%">
      <el-row :span="24">
        <el-col>
          <el-input v-model="content" placeholder="请输入内容" @keyup.enter.native="sendMsg" />
        </el-col>
      </el-row>
    </div>

    <!-- 发送消息 -->
    <div class="mtop" style="height: 5%">
      <el-row :span="24">
        <el-col>
          <el-button class="btn" type="primary" @click="sendMsg">发 送</el-button>
        </el-col>
      </el-row>
    </div>
  </div>

  <el-dialog v-model="show" title="请输入昵称" width="80%">
    <el-input v-model="name" placeholder="请输入昵称" clearable>
      <template #append>
        <el-button @click="join">加入</el-button>
      </template>
    </el-input>
  </el-dialog>

</template>

<script>
  import chat from '../../api/chat';
  import globalApi from '../../api/globalApi';
  export default {
    data () {
      return {
        date: new Date().toLocaleString(),
        name: '',
        count: 0,
        content: '',
        msgRecord: [],
        toUserId: '',
        msg: {
          content: '',
          id: 0,
          ip: '',
          region: '',
          itime: '',
          sender: '系统通知',
          toUserId: '',
        },
        show: name === '',
        ipInfo: null
      }
    },

    mounted () {
      // 获取用户IP
      this.getIp()
      // 获取消息记录
      this.getMsg()
      // 当前时间定时器
      const _this = this // 声明一个变量指向Vue实例this，保证作用域一致
      this.timer = setInterval(() => {
        _this.date = new Date().toLocaleString() // 修改数据date
      }, 1000)
    },

    // 当关闭页面时关闭链接（自动下线）
    destroyed () {
      this.wsClose()
    },
    methods: {
      // 初始化服务器建立连接
      initWebSocket () {
        // WebSocket与普通的请求所用协议有所不同，ws等同于http，wss等同于https
        // 本地： 127.0.0.1:9999
        // 线上： chat.zoubya.cn
        // 随机数：Math.floor(Math.random() * 100)
        this.websock = new WebSocket(
          process.env.VUE_APP_WEBSOCKET_URL + '/chat/im/' + this.name
        )
        this.websock.onopen = this.wsOpen
        this.websock.onerror = this.wsError
        this.websock.onmessage = this.wsMessage
        this.websock.onclose = this.wsClose
      },
      wsOpen (e) {
        console.log(e)
      },
      wsMessage (e) {
        console.log('收到消息：' + e.data)
        const msg = JSON.parse(e.data)
        // 0:实时更新在线人数
        if (msg.signal === '0') {
          this.count = msg.value
          this.msg.content = msg.desc
          this.msgRecord = this.msgRecord.concat(this.msg)
        }
        // 1:实时更新最新消息
        else if (msg.signal === '1') {
          this.getMsg()
        }
      },
      wsClose (e) {
        console.log('connection closed => ' + e)
      },
      wsError (e) {
        console.log('WebSocket连接发生错误 => ' + e)
      },

      // 加入群聊
      join () {
        this.initWebSocket()
        this.show = false;
      },

      // 获取消息记录
      async getMsg () {
        this.msgRecord = await chat.getMsg()
        this.$nextTick(() => { this.scrollToBottom() });
      },

      // 发送消息
      async sendMsg () {
        if (this.content !== '') {
          const params = {
            toUserId: this.toUserId,
            content: this.content,
            ip: this.ipInfo.ip,
            region: this.ipInfo.ad_info.city + this.ipInfo.ad_info.district
          }
          this.websock.send(JSON.stringify(params))
          this.content = ''
        } else {
          console.info('发送消息不能为空')
        }
      },
      // 滚动条置底
      scrollToBottom () {
        // console.log(this.$refs.content.scrollHeight)
        // 这里设置了固定值高度，因为聊天记录只会返回最新的30条记录，设置2000可以实现置底效果，如果是分页的话，就要实时更新高度了
        this.$refs.myScrollbar.scrollTop = [0, 1]
        this.$refs.myScrollbar.setScrollTop(3000)
      },
      getIp () {
        globalApi.getIPAddress().then(response => {
          console.log(response)
          if (response.status === 0) { // 请求成功
            this.ipInfo = response.result
          }
        }).catch(err => {
          console.log(err)
        });
      }
    },
  }
</script>

<style scoped>
  .main-cls {
    /* background-color: black; */
    height: 100%
  }



  .title-cls {
    display: flex;
    align-items: center;
    /*定义body的元素垂直居中*/
    justify-content: center;
    /*定义body的里的元素水平居中*/
    height: 10%;
    font-size: 22px;
    font-weight: bold;
  }

  .content-cls {
    height: 65%;
    border: rgb(218, 215, 215) 1px solid;
    border-radius: 5px;
    font-size: 12px;
    color: rgb(135, 160, 172);
    margin-top: 10px;
    padding: 10px;
    /* background-color: rgb(40, 42, 48); */
  }

  .content-left {
    /* 居右 */
    align-items: flex-start;
  }

  .content-right {
    /* 居右 */
    align-items: flex-end;
  }

  .content-left,
  .content-right {
    display: flex;
    flex-direction: column;
    /*垂直居中*/
    justify-content: center;
    height: 60px;
  }

  .mtop {
    margin-top: 2%;
  }

  .btn {
    width: 100%;
  }

  .onlineCount {
    font-size: 15px;
  }

  .itime {
    color: rgb(185, 182, 182);
  }
</style>